package com.stone.framework.batch.tasklet;

import java.io.File;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

/**
 * 文件重命名 tasklet
 * 
 * @author ybliu
 * @date 2020/07/27
 */
public class FileRenamingTasklet implements Tasklet, InitializingBean {

    private Resource resource;
    private String currentChar;
    private String newChar;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        File file = this.resource.getFile();
        if (!file.exists()) {
            throw new RuntimeException(this.resource.getFilename());
        }
        File target = new File(file.getPath().replace(this.currentChar, this.newChar));
        if (target.exists()) {
            target.delete();
        }
        file.renameTo(target);

        contribution.setExitStatus(ExitStatus.COMPLETED);
        return RepeatStatus.FINISHED;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.resource, "resource must not be null");
        Assert.notNull(this.currentChar, "currentChar must not be null");
        Assert.notNull(this.newChar, "newChar must not be null");
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public void setCurrentChar(String currentChar) {
        this.currentChar = currentChar;
    }

    public void setNewChar(String newChar) {
        this.newChar = newChar;
    }

}
